#-*-coding=utf8-*-
'''
Created on 2014年5月7日

@author: george
'''

from bs4 import BeautifulSoup
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
import urllib
import urllib2

#sender information

# 163.com
SENDER = 'gongjun0208@163.com'
SMTPSERVER = 'smtp.163.com'
USERNAME = 'gongjun0208'
PASSWORD = 'g-1812998535'
SSL = 0

#qq.com
# SENDER = '173926387@qq.com'
# SMTPSERVER = 'smtp.qq.com'
# USERNAME = '173926387@qq.com'
# PASSWORD = 'g-1812998535a'
# SSL = 1

def send_plain_mail(subject,context,receiver_list):

    msg = MIMEText(context,'plain','utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    _context = msg.as_string()
    
    
    return _smtp_server_send(receiver_list,_context)

def send_html_mail(subject,context,receiver_list):
    
    msg = MIMEText(context,'html','utf-8')
    msg['Subject'] = Header(subject, 'utf-8')
    _context = msg.as_string()

    return _smtp_server_send(receiver_list,_context)


def send_htmlWithPic_mail(subject,context,receiver_list):
    
    #html part
    msg_text = MIMEText(context,'html','utf-8')
    with open('girl_cute.gif', 'rb') as f:
        image_file = f.read()
    
    #image part
    msg_image = MIMEImage(image_file)  
    msg_image.add_header('Content-ID', '<image1>')
    
    #root part and attach html and image
    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject, 'utf-8')
    msg.attach(msg_text)
    msg.attach(msg_image)
    
    _context = msg.as_string()

    return _smtp_server_send(receiver_list,_context)


def send_attachment_mail(subject,context,receiver_list):
    
    #text part
    msg_text = MIMEText(context,'plain','utf-8')
    
    #atachment part
    with open('girl_cute.gif', 'rb') as f:
        atta = f.read()
    msg_atta = MIMEText(atta,'base64','utf-8')
    msg_atta["Content-Type"] = 'application/octet-stream'
    msg_atta["Content-Disposition"] = 'attachment; filename="girl_cute.gif"'
    
    #root part and attach text and attacment
    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject, 'utf-8')
    msg.attach(msg_text)
    msg.attach(msg_atta)
    
    _context = msg.as_string()
    
    return _smtp_server_send(receiver_list,_context)
    

def _smtp_server_send(receiver_list,context):
    
    result = True
    
    if SSL:
        smtp = smtplib.SMTP_SSL()
    else:
        smtp = smtplib.SMTP()
    try: 
        smtp.connect(SMTPSERVER)  
        smtp.login(USERNAME, PASSWORD)  
        smtp.sendmail(SENDER, receiver_list, context)
    except Exception,e:
        result = False
        import traceback;traceback.print_exc()
    finally:    
        smtp.quit()
    
    return result


def send_qiushi_email(qiushi,subject,receiver_list):
    """
        get qiushibaike context and send email
        qiushi structrue
        [(_time,_context,_img),...]
        
        _time : post the qiushi time
        _context : the qiushi context
        _img : image url if have
        
    """
    context = []
#     qiushi = get_qiushi()
    image_num = 0
    image_list = []
    
    msg = MIMEMultipart('related')
    msg['Subject'] = Header(subject, 'utf-8')
    for _qiushi in qiushi:
        image_num += 1
        _time,_context,img_src = _qiushi
        context.append('<div>')
        context.append(_context)
        context.append('<br>')
        
        if img_src:
#             file_name = img_src.split('/')[-1]
            #result:
            #('/tmp/tmp2zjur8.jpg', <httplib.HTTPMessage instance at 0x1722c68>)
            result = urllib.urlretrieve(img_src)
            image_file = result[0]
            with open(image_file,'r') as f:
                image = f.read()
            #image part
            msg_image = MIMEImage(image)
            msg_image.add_header('Content-ID', '<image%d>'%image_num)
            img_html = '<img src="cid:image%d" />'%image_num
            context.append(img_html)
            image_list.append(msg_image)
            
        context.append('</div><br>')
            
    #html part
    context = ''.join(context)
    html="<html><body>%s</body></html>"%context
    
    msg_text = MIMEText(html,'html','utf-8')
    
    msg.attach(msg_text)
    for image in image_list:
        msg.attach(image)
    
    _text = msg.as_string()

    return _smtp_server_send(receiver_list,_text)


def get_qiushi():
    USER_AGENT= ("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:28.0) " 
                 "Gecko/20100101 Firefox/28.0")
    url = "http://www.qiushibaike.com"
    
    headers = {"User-Agent":USER_AGENT}
    
    req = urllib2.Request(url,headers=headers)
    rlt = urllib2.urlopen(req)
    
    html = rlt.read()
    
    soup = BeautifulSoup(html)
    
    div_contents = soup.find_all('div',class_="content")
    
    qiushi = []
    
    for content in div_contents:
        _time = content.get('title')
        _context = content.get_text(strip=True)
        _img = ''
        
        _next = content.find_next_sibling()
        if _next['class'][0] == "thumb":
            _img = _next.a.img['src']
        qiushi.append((_time,_context,_img))
    
    return qiushi
        
        
if __name__ == "__main__":
    receiver = ['gongjun0208@gmail.com']
    subject = 'qiushibaike'
    send_qiushi_email(subject,receiver)
    
#     with open('mailcontext','r') as f:
#         context = f.read()
#     
#     print send_plain_mail(subject,context,receiver)